<template>
  <div class="imgUpload">
    <div>{{ browsermsg }}</div>
    <div v-if="listType ==='image'">
      <div class="img_list">
        <div v-for="(item,index) in UploadObj" :key="index" class="img_li">
          <img :src="item.src">
          <el-progress :percentage="item.percentage" :color="customColor" class="progress-bar" />
        </div>
        <div :id="id" class="upimage">
          <i class="el-icon-plus avatar-uploader-icon" />
        </div>
      </div>
    </div>
    <div v-for="(item,index) in UploadObj" :key="index">
      <div v-if="listType ==='doc'">
        <div>
          <i class="el-icon-document" />
          {{ item.name }} {{ item.size }}
          <el-button
            v-if="!(item.percentage == 100)"
            type="danger"
            size="mini"
            icon="el-icon-delete"
            circle
            @click="deleteClick(index)"
          />
        </div>
        <el-progress :percentage="item.percentage" :color="customColor" class="progress-bar" />
      </div>
    </div>
    <div id="container">
      <a v-if="listType !=='image'" :id="id" href="javascript:void(0);" class="btn">选择文件</a>
      <a href="javascript:void(0);" class="btn" @click="set_upload_param(plUploader)">开始上传</a>
    </div>
    <pre id="console" />
  </div>
</template>
<script>
import plupload from 'plupload'
import { getFileToken } from '@/api/general/file'
export default {
  model: {
    prop: 'file',
    event: 'cc'
  },
  props: {
    file: {
      type: Array,
      default: () => []
    },
    msg: {
      type: Object,
      default: () => { }
    },
    id: {
      type: String,
      default: () => `btn-${Date.now()}`
    },
    listType: {
      type: String,
      default: 'doc'
    },
    multiple: {
      type: Boolean,
      default: () => false
    },
    maxFileSize: {
      type: String,
      default: '10mb'
    }
  },
  data() {
    return {
      url: this.msg || '',
      browsermsg: '你的浏览器不支持flash,Silverlight或者HTML5！',
      UploadObj: [],
      customColor: '',
      percentage: 0,
      plUploader: null
    }
  },
  created() { },
  mounted() {
    this.initPlUploader()
  },
  beforeDestroy() {
    this.plUploader.destroy()
  },
  methods: {
    deleteClick(index) {
      this.UploadObj.splice(index, 1)
      this.plUploader.files.splice(index, 1)
    },

    set_upload_param(up) {
      const g_object_name = this.random_string(10)
      this.gettoken().then(res => {
        const new_multipart_params = {
          key: `${res.dir}${g_object_name}`,
          policy: res.policy,
          OSSAccessKeyId: res.accessid,
          success_action_status: '200', // 让服务端返回200,不然，默认会返回204
          callback: res.callback,
          signature: res.signature
        }
        up.setOption({
          url: res.host,
          multipart_params: new_multipart_params
        })
        up.start()
      })
    },

    gettoken() {
      const dir = 'elec/'
      return new Promise((resolve, reject) => {
        getFileToken({ dir }).then(result => {
          resolve(result.data)
        })
      })
    },

    error(up, err) {
      this.$message.error('上传失败')
    },

    FilesRemoved(uploader, files) {
      console.log(files)
    },

    fileUploaded(up, file, info) {
      if (info.status === 200) {
        const res = JSON.parse(info.response)
        this.UploadObj.find(val => file.id === val.id).fileId = res.fileId
        const fileList = this.UploadObj.filter(item => {
          if (item.fileId) {
            return item
          }
        })
        this.$nextTick(() => {
          this.$emit('cc', fileList.map(item => item.fileId))
        })
        this.$message.success('上传成功')
      } else {
        this.$message.error('上传失败')
      }
    },
    uploadProgress(up, file) {
      this.UploadObj.find(val => file.id === val.id).percentage = file.percent
    },

    beforeUpload(up, files) { },

    initPlUploader() {
      const _that = this
      this.plUploader = new plupload.Uploader({
        runtimes: 'html5,flash,silverlight,html4',
        url: 'http://oss.aliyuncs.com',
        browse_button: _that.id,
        multi_selection: _that.multiple,
        filters: {
          mime_types: [
            { title: 'Image files', extensions: 'jpg,gif,png,bmp' },
            { title: 'Zip files', extensions: 'zip,rar,ipa' }
          ],
          max_file_size: _that.maxFileSize, // 最大只能上传10mb的文件
          prevent_duplicates: true // 不允许选取重复文件
        },
        init: {
          PostInit: () => {
            _that.browsermsg = ''
          },
          FilesAdded: (up, files) => {
            plupload.each(files, file => {
              const _URL = window.URL || window.webkitURL
              const img = new Image()
              img.src = _URL.createObjectURL(file.getNative())
              _that.UploadObj = [
                ..._that.UploadObj,
                { ...file, size: plupload.formatSize(file.size), fileId: '', percentage: 0, src: img.src }
              ]
            })
            console.log('有新文件添加至队列')
          },
          BeforeUpload: this.beforeUpload,
          UploadProgress: this.uploadProgress,
          FileUploaded: this.fileUploaded,
          FilesRemoved: this.FilesRemoved,
          Error: this.error
        }
      })
      this.plUploader.init()
    },

    random_string(len) {
      len = len || 32
      const chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
      const maxPos = chars.length
      let pwd = ''
      for (let i = 0; i < len; i++) {
        pwd += chars.charAt(Math.floor(Math.random() * maxPos))
      }
      return pwd
    }
  }
}
</script>
<style>
.imgUpload .el-progress-bar .el-progress-bar__outer .el-progress-bar__inner {
  box-shadow: rgba(0, 0, 0, 0.14902) 0px -1px 0px 0px inset;
  background-image: linear-gradient(
    45deg,
    rgba(255, 255, 255, 0.14902) 25%,
    transparent 25%,
    transparent 50%,
    rgba(255, 255, 255, 0.14902) 50%,
    rgba(255, 255, 255, 0.14902) 75%,
    transparent 75%,
    transparent
  );
}
</style>
<style scoped lang="scss">
.img_list {
  display: flex;
  padding-bottom: 50px;
}
.img_li {
  margin-right: 10px;
  width: 148px;
  height: 148px;
  img{
    width: 148px;
    height: 148px;
  }
}
.btn {
  color: #fff;
  background-color: #337ab7;
  border-color: #2e6da4;
  display: inline-block;
  padding: 6px 12px;
  margin-bottom: 0;
  font-size: 14px;
  font-weight: 400;
  line-height: 1.42857143;
  text-align: center;
  white-space: nowrap;
  text-decoration: none;
  vertical-align: middle;
  -ms-touch-action: manipulation;
  touch-action: manipulation;
  cursor: pointer;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  background-image: none;
  border: 1px solid transparent;
  border-radius: 4px;
}
a.btn:hover {
  background-color: #3366b7;
}
.upimage {
  width: 200px;
  height: 200px;
  background-color: #fbfdff;
  border: 1px dashed #c0ccda;
  box-sizing: border-box;
  width: 148px;
  height: 148px;
  cursor: pointer;
  line-height: 146px;
  vertical-align: top;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
